/*+***********************************************************************************
 Filename: 02_verilog_step05\src\top.v
 Description: Examples for demo the usage of FSM and case.

 Modification:
   2022.10.05 Creation   H.Zheng

Copyright (C) 2022  Zheng Hui (hzheng@gzhu.edu.cn)

License: MulanPSL-2.0

***********************************************************************************-*/

module top
(
    input wire [1:0] button,
    input wire sys_clk,
    input uart0_rxd,          
    output uart0_txd,
    output wire [5:0] led
);



//sample 5: marquee led.

//use 1s counter trigger the shift.

reg [6:0] counter1;
wire reset_n;
reg clk_206T0;

always @(posedge sys_clk or negedge reset_n) begin
    if (~reset_n) begin
	    counter1 <= 0;
        clk_206T0 <=0;
	end
	else begin
        if (counter1 >= 102) begin
            counter1 <= 0;
            clk_206T0 <= ~clk_206T0;
        end
        else begin
	        counter1 <= counter1 + 1'b1;
        end    
	end
end

reg [16:0] counter2;

always @(posedge clk_206T0 or negedge reset_n) begin
    if (~reset_n) begin
	    counter2 <= 0;
	end
	else begin
	    counter2 <= counter2 + 1'b1;
	end
end

wire clk_1s = counter2[16];

//round shift
reg [5:0] led_value;

always @(posedge clk_1s or negedge reset_n) begin
    if (~reset_n) begin
	    led_value <= 6'b000011;  //initial pattern of leds
	end
    else begin
	    led_value <= {led_value[4:0], led_value[5]};
	end
end

//assoiciate pins
assign reset_n = button[1];
assign led = ~led_value;




//uart rx
wire [7:0] uart_rx_data;
wire uart_rx_flag;

uart_rx #(.BAUDRATE_DIVIDER(234)) u_uart0_rx(  
   .clk(sys_clk),  //27MHz
   .reset_n(reset_n),
   .rxd(uart0_rxd),
   .rx_data(uart_rx_data),
   .rx_flag(uart_rx_flag)
);


// uart tx

//wire uart_tx_en = (counter2[16:0] == 17'b1); //trigger tx every 1s
//wire [7:0] uart_tx_data = {~button, ~led};
wire uart_tx_en1 = (counter2[16:0] == 17'b1); //trigger tx every 1s
wire [7:0] uart_tx_data1 = {~button, ~led};

wire uart_tx_en = uart_rx_flag | uart_tx_en1;
wire [7:0] uart_tx_data = uart_rx_flag ? uart_rx_data : uart_tx_data1;

//Baudrate=9600; DIVIDER=27,000,000/9600=2812.5
//uart_tx #(.BAUDRATE_DIVIDER(2812)) u_uarttx(  
//Baudrate=115200; DIVIDER=27,000,000/115200=234.375
uart_tx #(.BAUDRATE_DIVIDER(234)) u_uart0_tx(  
   .clk(sys_clk),  //27MHz
   .reset_n(reset_n),
   .tx_en(uart_tx_en),
   .tx_data(uart_tx_data),
   .txd(uart0_txd)
);


endmodule